package com.baiyinet.util;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;

import com.baiyinet.BuildConfig;
import com.baiyinet.R;
import com.baiyinet.biz.CurrentUser;
import com.baiyinet.biz.PageStatus;
import com.baiyinet.rest.ApiHelper;
import com.baiyinet.rest.DownloadImgResponse;
import com.baiyinet.ui.general.GeneralActivity_;
import com.baiyinet.ui.share.ShareModeDialogActivity;
import com.baiyinet.ui.share.ShareMultiPicDialogActivity;
import com.baiyinet.util.task.OneKeyDownloadImageTask;
import com.baiyinet.util.task.SingleDownloadImageTask;

import org.parceler.Parcels;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;

import rx.Subscriber;
import timber.log.Timber;

/**
 * @author J.Huang
 * @version 1.0
 * @since 16/12/16
 */

public class DialogUtils {

    private static Dialog mDialog;

    /**
     * 显示在别台设备登录对话框
     * @param activity
     * @param
     */
    public static void showUserMultiLoginDialog(final Activity activity, final CurrentUser currentUser) {
        try {
            String msg = "您的账号已在另外一台设备登录！";

            if (activity == null || TextUtils.isEmpty(msg)) {
                return;
            }
            if(null != mDialog && mDialog.isShowing()) {
                return;
            }

            if (mDialog == null) {
                AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                builder.setMessage(msg);
                builder.setTitle("下线通知");
                builder.setPositiveButton("", null);
                builder.setNegativeButton("退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        currentUser.logout();
                        if (currentUser.needLogin()) {
                            IntentUtils.toLogin(activity);
                        } else {
                            IntentUtils.toMain(activity);
                        }
                    }
                });
                builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        dismissDialog();
                    }
                });
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            dismissDialog();
                        }
                    });
                }
                builder.setCancelable(false);
                mDialog = builder.create();
            }
            mDialog.show();
        }catch (Exception e) {
            e.printStackTrace();
            dismissDialog();
            showUserMultiLoginDialog(activity, currentUser);
        }
    }

    /**
     * 显示下载对话框
     * @param activity 上下文
     * @param url 下载地址
     */
    public static void showUpdateDialog(final Activity activity, final String url, final SharedPreferences sharedPref) {
        try {
            if (activity == null || TextUtils.isEmpty(url)) {
                return;
            }
            if (mDialog != null && mDialog.isShowing()) {
                return;
            }

//            mDialog = new Dialog(activity, R.style.BaseDialog);
//            View view = LayoutInflater.from(activity).inflate(
//                    R.layout.dialog_confirm, null);
//            TextView txvMsg =  (TextView) view.findViewById(R.id.txv_dialog_msg);
//            TextView txvTitle = (TextView) view.findViewById(R.id.txv_dialog_title);
//            txvTitle.setText("提示");
//            txvMsg.setText("发现新版本，是否更新？");
//
//            view.findViewById(R.id.btn_dialog_no).setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    dismissDialog();
//                    activity.finish();
//                }
//            });
//            view.findViewById(R.id.btn_dialog_ok).setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    dismissDialog();
//
//                    showProgressDialog(activity, "下载更新包中…");
//
//                    // 删除原有安装包
//                    File file = new File(
//                            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
//                                    + activity.getResources().getString(R.string.app_name)+ ".apk");
//                    if(file.exists()) {
//                        file.delete();
//                    }
//
//                    // 调用系统下载
//                    DownloadManager dm = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
//                    DownloadManager.Request request = new DownloadManager.Request(
//                            Uri.parse(url));
//                    request.setMimeType("application/vnd.android.package-archive");
//                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
//                            activity.getResources().getString(R.string.app_name)+ ".apk");
//                    // 设置为可被媒体扫描器找到
//                    request.allowScanningByMediaScanner();
//                    // 设置为可见和可管理
//
//                    request.setVisibleInDownloadsUi(true);
//                    long reference = dm.enqueue(request);
//                    SharedPreferences.Editor editor = sharedPref.edit();
//                    editor.putLong("downloadApkRef", reference);
//                    editor.apply();
//                }
//            });
//
//            mDialog.setContentView(view);
//            mDialog.setCanceledOnTouchOutside(false);
//            mDialog.setCancelable(false);
//            mDialog.show();

            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setTitle("提示");
            builder.setMessage("发现新版本，请下载更新包！");
            builder.setNegativeButton("下次再说", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dismissDialog();
                }
            });
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dismissDialog();

                    showProgressDialog(activity, "下载更新包中…");

                    // 删除原有安装包
                    File file = new File(
                            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                                    + File.separator + activity.getResources().getString(R.string.app_name)+ ".apk");
                    if(file.exists()) {
                        file.delete();
                    }

                    // 调用系统下载
                    DownloadManager dm = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
                    DownloadManager.Request request = new DownloadManager.Request(
                            Uri.parse(url));
                    request.setMimeType("application/vnd.android.package-archive");
                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                            activity.getResources().getString(R.string.app_name)+ ".apk");
                    // 设置为可被媒体扫描器找到
                    request.allowScanningByMediaScanner();
                    // 设置为可见和可管理

                    request.setVisibleInDownloadsUi(true);
                    long reference = dm.enqueue(request);
                    SharedPreferences.Editor editor = sharedPref.edit();
                    editor.putLong("downloadApkRef", reference);
                    editor.apply();
                }
            });
            builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    dismissDialog();
                }
            });
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        dismissDialog();
                    }
                });
            }
            builder.setCancelable(false);
            mDialog = builder.create();
            mDialog.show();
        }catch (Exception e) {
            e.printStackTrace();
            dismissDialog();
        }
    }

    /**
     * 显示加载进度
     * @param activity
     * @param msg
     */
    public static void showProgressDialog(Activity activity, String msg) {
        try {
            if (activity == null) {
                return;
            }
            if (mDialog != null && mDialog.isShowing()) {
                return;
            }

            ProgressDialog dialog = ProgressDialog.show(activity, "", msg);
            dialog.setCanceledOnTouchOutside(false);
            dialog.setCancelable(false);

            mDialog = dialog;
            mDialog.show();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示图片保存提示框
     * @param context
     * @param imgUrl
     */
    public static void showImgSaveDialog(final Context context, final String imgUrl) {
        if (context == null) {
            return;
        }
        if (mDialog != null && mDialog.isShowing()) {
            return;
        }

        View saveView = LayoutInflater.from(context).inflate(R.layout.layout_pop_img_save, null);

        saveView.findViewById(R.id.btn_save_img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismissDialog();
                new SingleDownloadImageTask(context,"图片已保存到:").execute(imgUrl);
//                new DownloadImageTask(context, "图片已保存到:").execute(imgUrl);
            }
        });
        saveView.findViewById(R.id.btn_cancel_img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismissDialog();
            }
        });

        mDialog = new Dialog(context, R.style.CustomDialog);
        mDialog.setContentView(saveView);
        mDialog.setCanceledOnTouchOutside(true);
        WindowManager.LayoutParams params = mDialog.getWindow().getAttributes();
        int width = context.getResources().getDisplayMetrics().widthPixels;
        int height = (int) (context.getResources().getDisplayMetrics().heightPixels * 0.3);
        params.width = width;
        params.height = height;
        mDialog.getWindow().setAttributes(params);
        mDialog.getWindow().setGravity(Gravity.BOTTOM);
        mDialog.show();
    }

    private static class DownloadImgSubscriber extends Subscriber<DownloadImgResponse> {

        private Activity mActivity;
        private String  mJsFun;

        /***
         *
         * @param activity
         */
        public DownloadImgSubscriber(Activity activity, String jsFun) {
            mActivity = activity;
            mJsFun = jsFun;
        }

        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            Timber.d(e.toString());
            dismissDialog();
            Utils.UI.showToastShort("图片保存失败");
        }

        @Override
        public void onNext(DownloadImgResponse downloadImgResponse) {
            Timber.d(downloadImgResponse.toString());

            if (downloadImgResponse.Total < 1) {
                dismissDialog();
                Utils.UI.showToastShort("图片保存失败");
            } else {
                List<String> imgUrlList = new ArrayList<>();

                for (String imgUrl : downloadImgResponse.Data) {
                    if (!imgUrl.startsWith("http")) {
                        imgUrl = BuildConfig.ENDPOINT + imgUrl;
                    }
                    imgUrlList.add(imgUrl);
                }

                // 下载图片
                OneKeyDownloadImageTask task = new OneKeyDownloadImageTask(mActivity, mDialog);
                task.setImagesSaveCallBack(new ShareImagesCallBack(mActivity, mJsFun));
                task.execute(imgUrlList);
            }
        }
    }

    /**
     * 一键保存多张图片提示框
     * @param activity
     * @param attachData
     */
    public static void  showImgOneKeySaveAllDialog(Activity activity, ApiHelper apiHelper, String attachData, String successFun) {
        if (activity == null) {
            return;
        }
        if (mDialog != null && mDialog.isShowing()) {
            return;
        }

        mDialog = ProgressDialog.show(activity, "", "图片保存中…");
        mDialog.show();

        Map<String, String> params = new WeakHashMap<>();
        params.put("AttachData", attachData);
        DownloadImgSubscriber subscriber = new DownloadImgSubscriber(activity, successFun);
        apiHelper.downloadImg(subscriber, params);
    }

    public static void showConfirmBackDialog(final Activity activity) {
        try {
            if (activity == null) {
                return;
            }
            if (mDialog != null && mDialog.isShowing()) {
                return;
            }

            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setTitle("提示");
            builder.setMessage("确定放弃编辑吗？");
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dismissDialog();
                }
            });
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dismissDialog();
                    activity.finish();
                }
            });
            builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    dismissDialog();
                }
            });
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        dismissDialog();
                    }
                });
            }
            builder.setCancelable(false);
            mDialog = builder.create();
            mDialog.show();
        }catch (Exception e) {
            e.printStackTrace();
            dismissDialog();
        }
    }

    /**
     * 隐藏对话框
     */
    public static void dismissDialog() {
        if (mDialog != null) {
            mDialog.dismiss();
            mDialog = null;
        }
    }

    /**
     * 分享图片下载回调
     */
    private static class ShareImagesCallBack implements OneKeyDownloadImageTask.ImagesSaveCallBack {

        private Activity mActivity;
        private String mJsFun = "";

        public ShareImagesCallBack(Activity activity, String jsFun) {
            mActivity = activity;
            mJsFun = jsFun;
        }

        @Override
        public void onSuccess(List<String> list) {
//            if (!TextUtils.isEmpty(mJsFun) && list != null && list.size() > 0) {
            if (list != null && list.size() > 0) {
                if (mActivity instanceof ShareModeDialogActivity) {
                    // 多图分享
                    ArrayList<Uri> imageUris = new ArrayList<>();
                    for (int i = 0; i < list.size(); i++) {
                        imageUris.add(Uri.fromFile(new File(list.get(i))));
                    }

                    Intent intent = new Intent(mActivity, ShareMultiPicDialogActivity.class);
                    intent.putParcelableArrayListExtra("imageUris", imageUris);
                    mActivity.startActivity(intent);
                }

//                if (mActivity instanceof GeneralActivity_) {
//                    ((GeneralActivity_) mActivity).loadUrl("javascript:"+ mJsFun + "();");
//                    ((GeneralActivity_) mActivity).setDownloadedImgList(list);
//                } else if (mActivity instanceof MainActivity_) {
//                    ((MainActivity_) mActivity).loadUrl("javascript:"+ mJsFun + "();");
//                    ((MainActivity_) mActivity).setDownloadedImgList(list);
//                }
            }
        }
    }
}
